package com.zty.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import com.tencent.cloud.cos.util.Jackson;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author tyzhang19
 * @Description cos提供临时秘钥
 * @date 2022-08-17 16:55
 */
@RestController
@Slf4j
public class CosController {
    @RequestMapping(value = "/getSts",method = RequestMethod.GET)
    @ResponseBody
    public Object getSts() {
        Map result = new HashMap<>();
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        Response credential = null; // 凭证结果
        try {

            // 云 api 密钥 SecretId
            config.put("secretId", "AKIDtfEZfXCftteARTFm59yYtzqTu74mFTSB");
            // 云 api 密钥 SecretKey
            config.put("secretKey", "XpsgEXbR3QXP2QZT8anlUxBAyVnqeDYd");

            // 设置域名
            //config.put("host", "sts.internal.tencentcloudapi.com");

            // 临时密钥有效时长，单位是秒
            config.put("durationSeconds", 180);
            // 换成你的 bucket
            config.put("bucket","ztytest-1302338467");
            // 换成 bucket 所在地区
            config.put("region", "ap-beijing");

            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            config.put("allowPrefixes", new String[] {
                    "*"
            });

            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[] {
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:PostObject",
                    "name/cos:GetObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload",
                    "name/cos:GetBucket"
            };
            config.put("allowActions", allowActions);
            // 添加一批资源路径
            // 一条资源的规则是：qcs::cos:<REGION>:uid/<APPID>:<BUCKET-APPID>/<OBJECT>
//            String[] allowResource= new String[] {
//                    "qcs::cos:ap-beijing:uid/appid:/"
//            };
//            config.put("allowResource",allowResource);

            credential  = CosStsClient.getCredential(config);
            System.out.println(Jackson.toJsonPrettyString(credential));

            result.put("code", 20000);
            result.put("data",credential );
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("no valid secret !");
        }
    }

    @RequestMapping(value = "/vue-element-admin/user/login",method = RequestMethod.POST)
    @ResponseBody
    public Map login(){
        Map result = new HashMap();
        result.put("code", 20000);
        result.put("data", "admin-token");
        return result;
    }

    @RequestMapping(value = "/vue-element-admin/user/info",method = RequestMethod.GET)
    public Map useInfo(){
        List<String> list = Arrays.asList("admin");
        Map data = new HashMap();
        data.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        data.put("introduction", "I am a super administrato");
        data.put("name", "Tom");
        data.put("roles", list);
        Map result = new HashMap();
        result.put("code", 20000);
        result.put("data", data);
        return result;
    }

    @RequestMapping(value = "/down", method = RequestMethod.GET)
    public Object downFile(@RequestParam(value = "path")String path) {
        System.out.println("============================="+path);
        TransferManager transferManager = createTransferManager();

        String bucketName = "ztytest-1302338467";
        String downUrl = "C:" + "/files/" + path;
        File downloadFile = new File(downUrl);

        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
        try {
            // 返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
            Download download = transferManager.download(getObjectRequest, downloadFile);
            download.waitForCompletion();
            return "下载成功";
        } catch (CosClientException | InterruptedException e) {
            return "下载失败";
        }finally {
            shutdownTransferManager(transferManager);
        }
    }

    public TransferManager createTransferManager() {
        // 创建一个 COSClient 实例，这是访问 COS 服务的基础实例。
        // 详细代码参见本页: 简单操作 -> 创建 COSClient
        COSClient cosClient = createCOSClient();

        // 自定义线程池大小，建议在客户端与 COS 网络充足（例如使用腾讯云的 CVM，同地域上传 COS）的情况下，设置成16或32即可，可较充分的利用网络资源
        // 对于使用公网传输且网络带宽质量不高的情况，建议减小该值，避免因网速过慢，造成请求超时。
        ExecutorService threadPool = Executors.newFixedThreadPool(32);

        // 传入一个 threadpool, 若不传入线程池，默认 TransferManager 中会生成一个单线程的线程池。

        return new TransferManager(cosClient, threadPool);
    }

    public COSClient createCOSClient(){
        String secretId = "AKIDtfEZfXCftteARTFm59yYtzqTu74mFTSB";
        String secretKey = "XpsgEXbR3QXP2QZT8anlUxBAyVnqeDYd";
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region("ap-beijing");
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    public void shutdownTransferManager(TransferManager transferManager) {
        transferManager.shutdownNow(true);
    }


}

